#include "ASTargetEntity.h"

NS_AS_BEGIN

ASTargetEntity::ASTargetEntity(int nAttrsNumI,int nAttrsNumF):
ASEntity(nAttrsNumI,nAttrsNumF),
_pTarget(nullptr)
{
}
ASTargetEntity::~ASTargetEntity()
{
	clearTargetAndListeners();
}
void ASTargetEntity::destory()
{
	clearTargetAndListeners();
	ASEntity::destory();
}
void ASTargetEntity::setTarget(ASTargetEntity* pNewTarget)
{
	if(_pTarget!=pNewTarget)
	{
		if(pNewTarget)
		{//add myself into new target's listener array
			pNewTarget->_vListeners.push_back(this);
		}
		if(_pTarget)
		{//if has old target,then remove myself from old target's listener array;
			std::vector<ASTargetEntity*>::iterator itfind = std::find(_pTarget->_vListeners.begin(),_pTarget->_vListeners.end(),this);
			if(itfind!=_pTarget->_vListeners.end())
			{
				_pTarget->_vListeners.erase(itfind);
			}
		}
		//assign new target
		_pTarget = pNewTarget;
		notifyTargetChange();
	}
}
ASTargetEntity* ASTargetEntity::getTarget()
{
	return _pTarget;
}
const std::vector<ASTargetEntity*>& ASTargetEntity::getListeners()
{
	return _vListeners;
}
unsigned int ASTargetEntity::getListenersNum()
{
	return _vListeners.size();
}
void ASTargetEntity::clearTargetAndListeners()
{
	setTarget(nullptr);//clear target
	for(std::vector<ASTargetEntity*>::iterator it=_vListeners.begin();it!=_vListeners.end();it++)
	{
		ASTargetEntity* pTarget = *it;
		ASAssert(pTarget->_pTarget==this,"");
		pTarget->_pTarget = nullptr;
		pTarget->notifyTargetChange();
	}
	_vListeners.clear();
}

NS_AS_END